<!--
# coding=UTF-8
# Copyright (c) 2025 Bird Software Solutions Ltd
# This program and the accompanying materials
# are made available under the terms of the Eclipse Public License 2.0
# which accompanies this distribution, and is available at
# https://www.eclipse.org/legal/epl-2.0/
#
# SPDX-License-Identifier: EPL-2.0
#
# Contributors:
#    Neil Mackenzie - initial API and implementation
#    Benjamin Arfa - improvements
#
-->
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>BPMN Metadata Lineage - {{ datapoint.combination_id }}</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            background-color: #f5f5f5;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .header {
            background-color: #2c3e50;
            color: white;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
        .header h1 {
            margin: 0;
            font-size: 24px;
        }
        .header p {
            margin: 5px 0 0 0;
            opacity: 0.8;
        }
        .controls {
            margin-bottom: 20px;
            padding: 15px;
            background-color: #ecf0f1;
            border-radius: 5px;
        }
        .btn {
            background-color: #3498db;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            margin-right: 10px;
            font-size: 14px;
        }
        .btn:hover {
            background-color: #2980b9;
        }
        .btn.success {
            background-color: #27ae60;
        }
        .btn.success:hover {
            background-color: #229954;
        }
        .btn.danger {
            background-color: #e74c3c;
        }
        .btn.danger:hover {
            background-color: #c0392b;
        }
        .status {
            margin: 10px 0;
            padding: 10px;
            border-radius: 4px;
            display: none;
        }
        .status.success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .status.error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .content {
            margin-top: 20px;
        }
        .section {
            margin-bottom: 20px;
            border: 1px solid #ddd;
            border-radius: 5px;
            overflow: hidden;
        }
        .section-header {
            background-color: #34495e;
            color: white;
            padding: 10px 15px;
            font-weight: bold;
            cursor: pointer;
        }
        .section-content {
            padding: 15px;
            display: none;
        }
        .section-content.expanded {
            display: block;
        }
        .task-item {
            background-color: #f8f9fa;
            margin: 10px 0;
            padding: 10px;
            border-radius: 4px;
            border-left: 4px solid #3498db;
        }
        .task-item.user-task {
            border-left-color: #e67e22;
        }
        .task-item.service-task {
            border-left-color: #27ae60;
        }
        .task-item h4 {
            margin: 0 0 5px 0;
            color: #2c3e50;
        }
        .task-item p {
            margin: 0;
            color: #666;
            font-size: 14px;
        }
        .flow-item {
            background-color: #fff3cd;
            margin: 5px 0;
            padding: 8px;
            border-radius: 4px;
            border-left: 4px solid #ffc107;
        }
        .json-output {
            background-color: #2c3e50;
            color: #ecf0f1;
            padding: 15px;
            border-radius: 4px;
            font-family: 'Courier New', monospace;
            font-size: 12px;
            overflow-x: auto;
            max-height: 500px;
            overflow-y: auto;
        }
        .checkbox {
            margin-right: 10px;
        }
        .legend {
            display: flex;
            justify-content: space-around;
            margin: 20px 0;
            padding: 15px;
            background-color: #f8f9fa;
            border-radius: 5px;
        }
        .legend-item {
            display: flex;
            align-items: center;
        }
        .legend-color {
            width: 20px;
            height: 20px;
            margin-right: 10px;
            border-radius: 3px;
        }
        .user-task-color { background-color: #e67e22; }
        .service-task-color { background-color: #27ae60; }
        .sequence-flow-color { background-color: #ffc107; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>BPMN Metadata Lineage</h1>
            <p>Datapoint: <strong>{{ datapoint.combination_id }}</strong></p>
            <p>BPMN-compliant representation of metadata lineage flows</p>
        </div>

        <div class="legend">
            <div class="legend-item">
                <div class="legend-color user-task-color"></div>
                <span>👤 UserTask (Input Data - Consumed)</span>
            </div>
            <div class="legend-item">
                <div class="legend-color service-task-color"></div>
                <span>⚙️ ServiceTask (Output Data - Produced)</span>
            </div>
            <div class="legend-item">
                <div class="legend-color sequence-flow-color"></div>
                <span>➡️ SequenceFlow (Data Transformation Process)</span>
            </div>
        </div>

        <!-- BPMN 2.0 Visualization -->
        <div class="section">
            <div class="section-header" onclick="toggleSection(this)">
                🎯 BPMN 2.0 Workflow Visualization
            </div>
            <div class="section-content expanded">
                <div class="visualization-controls" style="margin-bottom: 15px;">
                    <button class="btn" onclick="loadVisualization()">Load Visualization</button>
                    <button class="btn" onclick="exportVisualization()">Export as SVG</button>
                    <button class="btn" onclick="refreshVisualization()">Refresh</button>
                </div>
                <div id="bpmn-visualization" style="width: 100%; min-height: 600px; border: 1px solid #ddd; border-radius: 5px; background: #f9f9f9;">
                    <div style="text-align: center; padding: 50px; color: #666;">
                        <h3>BPMN 2.0 Workflow Diagram</h3>
                        <p>Click "Load Visualization" to display the BPMN workflow diagram</p>
                    </div>
                </div>
            </div>
        </div>

        <div class="controls">
            <button class="btn success" onclick="processBPMNLineage()">Process BPMN Lineage</button>
            <button class="btn" onclick="loadBPMNLineage()">Load Existing</button>
            <button class="btn danger" onclick="clearBPMNLineage()">Clear & Regenerate</button>
            <label class="checkbox">
                <input type="checkbox" id="clear-existing"> Clear existing before processing
            </label>
        </div>

        <div id="status" class="status"></div>

        <div class="content" id="content">
            <p>Click "Process BPMN Lineage" to generate the BPMN workflow for this datapoint.</p>
        </div>
    </div>

    <script src="{% static 'pybirdai/js/bpmn-lineage-viewer.js' %}"></script>
    <script>
        let currentLineageData = null;
        let bpmnViewer = null;
        
        // Initialize BPMN viewer when page loads
        document.addEventListener('DOMContentLoaded', function() {
            bpmnViewer = new BPMNLineageViewer('bpmn-visualization', {
                width: 1200,
                height: 800,
                nodeWidth: 140,
                nodeHeight: 80,
                levelGap: 250,
                nodeGap: 120
            });
            
            loadBPMNLineage();
        });

        function showStatus(message, isError = false) {
            const status = document.getElementById('status');
            status.textContent = message;
            status.className = 'status ' + (isError ? 'error' : 'success');
            status.style.display = 'block';
            
            setTimeout(() => {
                status.style.display = 'none';
            }, 5000);
        }

        function processBPMNLineage() {
            const clearExisting = document.getElementById('clear-existing').checked;
            
            showStatus('Processing BPMN metadata lineage...', false);

            const formData = new FormData();
            formData.append('clear_existing', clearExisting);

            fetch(`/pybirdai/datapoint/${encodeURIComponent('{{ datapoint_id }}')}/bpmn_metadata_lineage/process/`, {
                method: 'POST',
                body: formData,
                headers: {
                    'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showStatus(`BPMN lineage processed successfully! Output saved to: ${data.output_file}`, false);
                    currentLineageData = data.lineage;
                    renderBPMNLineage(data.lineage);
                    // Update visualization
                    if (bpmnViewer) {
                        bpmnViewer.renderLineage(data.lineage);
                    }
                } else {
                    showStatus(`Error: ${data.error}`, true);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showStatus(`Network error: ${error.message}`, true);
            });
        }

        function loadBPMNLineage() {
            showStatus('Loading existing BPMN lineage...', false);

            fetch(`/pybirdai/datapoint/${encodeURIComponent('{{ datapoint_id }}')}/bpmn_metadata_lineage/process/`)
            .then(response => response.json())
            .then(data => {
                if (data.success && data.lineage) {
                    if (data.lineage.user_tasks.length === 0 && data.lineage.service_tasks.length === 0) {
                        showStatus('No existing BPMN lineage found. Click "Process BPMN Lineage" to generate.', false);
                        document.getElementById('content').innerHTML = '<p>No BPMN lineage data available. Process lineage first.</p>';
                    } else {
                        showStatus('BPMN lineage loaded successfully!', false);
                        currentLineageData = data.lineage;
                        renderBPMNLineage(data.lineage);
                        // Update visualization
                        if (bpmnViewer) {
                            bpmnViewer.renderLineage(data.lineage);
                        }
                    }
                } else {
                    showStatus(`Error loading lineage: ${data.error || 'Unknown error'}`, true);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showStatus(`Network error: ${error.message}`, true);
            });
        }

        function clearBPMNLineage() {
            if (confirm('Are you sure you want to clear existing BPMN lineage and regenerate?')) {
                document.getElementById('clear-existing').checked = true;
                processBPMNLineage();
            }
        }

        function renderBPMNLineage(lineage) {
            const content = document.getElementById('content');
            
            let html = '';
            
            // Summary
            html += `
                <div class="section">
                    <div class="section-header" onclick="toggleSection(this)">
                        📊 BPMN Lineage Summary
                    </div>
                    <div class="section-content expanded">
                        <p><strong>UserTasks (Input):</strong> ${lineage.user_tasks.length}</p>
                        <p><strong>ServiceTasks (Output):</strong> ${lineage.service_tasks.length}</p>
                        <p><strong>SequenceFlows (Processes):</strong> ${lineage.sequence_flows.length}</p>
                        <p><strong>SubProcesses:</strong> ${lineage.subprocesses.length}</p>
                        <p><strong>WorkflowModules:</strong> ${lineage.workflow_modules.length}</p>
                    </div>
                </div>
            `;

            // UserTasks
            if (lineage.user_tasks.length > 0) {
                html += `
                    <div class="section">
                        <div class="section-header" onclick="toggleSection(this)">
                            🔵 UserTasks (Input Data - ${lineage.user_tasks.length})
                        </div>
                        <div class="section-content">
                `;
                
                lineage.user_tasks.forEach(task => {
                    html += `
                        <div class="task-item user-task">
                            <h4>${task.name}</h4>
                            <p><strong>ID:</strong> ${task.id}</p>
                            <p><strong>Description:</strong> ${task.description || 'N/A'}</p>
                            <p><strong>Entity Reference:</strong> ${task.entity_reference || 'N/A'}</p>
                        </div>
                    `;
                });
                
                html += '</div></div>';
            }

            // ServiceTasks
            if (lineage.service_tasks.length > 0) {
                html += `
                    <div class="section">
                        <div class="section-header" onclick="toggleSection(this)">
                            🟢 ServiceTasks (Output Data - ${lineage.service_tasks.length})
                        </div>
                        <div class="section-content">
                `;
                
                lineage.service_tasks.forEach(task => {
                    html += `
                        <div class="task-item service-task">
                            <h4>${task.name}</h4>
                            <p><strong>ID:</strong> ${task.id}</p>
                            <p><strong>Description:</strong> ${task.description || 'N/A'}</p>
                            <p><strong>Enriched Attribute Reference:</strong> ${task.enriched_attribute_reference || 'N/A'}</p>
                        </div>
                    `;
                });
                
                html += '</div></div>';
            }

            // SequenceFlows
            if (lineage.sequence_flows.length > 0) {
                html += `
                    <div class="section">
                        <div class="section-header" onclick="toggleSection(this)">
                            🟡 SequenceFlows (Data Transformation Processes - ${lineage.sequence_flows.length})
                        </div>
                        <div class="section-content">
                `;
                
                lineage.sequence_flows.forEach(flow => {
                    const sourceType = flow.source_type === 'UserTask' ? '🔵' : '🟢';
                    const targetType = flow.target_type === 'UserTask' ? '🔵' : '🟢';
                    
                    html += `
                        <div class="flow-item">
                            <h4>${flow.name}</h4>
                            <p><strong>Flow:</strong> ${sourceType} ${flow.source_ref || 'N/A'} → ${targetType} ${flow.target_ref || 'N/A'}</p>
                            <p><strong>Description:</strong> ${flow.description || 'N/A'}</p>
                        </div>
                    `;
                });
                
                html += '</div></div>';
            }

            // Raw JSON
            html += `
                <div class="section">
                    <div class="section-header" onclick="toggleSection(this)">
                        📄 Raw JSON Data
                    </div>
                    <div class="section-content">
                        <div class="json-output">${JSON.stringify(lineage, null, 2)}</div>
                    </div>
                </div>
            `;

            content.innerHTML = html;
        }

        function toggleSection(header) {
            const content = header.nextElementSibling;
            content.classList.toggle('expanded');
        }

        // Visualization control functions
        function loadVisualization() {
            if (currentLineageData && bpmnViewer) {
                showStatus('Loading BPMN visualization...', false);
                try {
                    bpmnViewer.renderLineage(currentLineageData);
                    showStatus('BPMN visualization loaded successfully!', false);
                } catch (error) {
                    showStatus(`Visualization error: ${error.message}`, true);
                }
            } else {
                showStatus('No lineage data available. Process lineage first.', true);
            }
        }

        function exportVisualization() {
            if (bpmnViewer) {
                try {
                    bpmnViewer.exportAsSVG();
                    showStatus('BPMN diagram exported as SVG!', false);
                } catch (error) {
                    showStatus(`Export error: ${error.message}`, true);
                }
            } else {
                showStatus('No visualization available to export.', true);
            }
        }

        function refreshVisualization() {
            if (currentLineageData && bpmnViewer) {
                showStatus('Refreshing BPMN visualization...', false);
                bpmnViewer.renderLineage(currentLineageData);
                showStatus('Visualization refreshed!', false);
            } else {
                loadBPMNLineage();
            }
        }
    </script>

    {% csrf_token %}
</body>
</html>